
package com.controller;


import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.model.Student;
import com.model.UserInfo;
import com.model.dto.LoginResultDTO;
import com.service.ClazzService;
import com.service.StudentService;
import com.utils.Pager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.UserEntity;
import com.service.TokenService;
import com.service.UserService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;

/**
 * 登录相关
 */
@RequestMapping("users")
@RestController
public class UserController{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private TokenService tokenService;

	@Resource
	private ClazzService clazzService;

	@Resource
	private StudentService studentService;


	@RequestMapping(value = "/updateInfo")
	public R updateInfo(Long id, String role, String username, String password) {
		if (StringUtils.equals(role, "student")) {
			studentService.updateStudentInfo(id, username, password);
		} else {
			userService.updateUserInfo(id, username, password);
		}
		return R.ok();
	}

	/**
	 * 登录
	 */
	@RequestMapping(value = "/login")
	public R login(String username, String password, String role) {
		LoginResultDTO resultDTO = new LoginResultDTO();
		if (role.equals("student")) {
			Student student = studentService.getStudentByName(username);
			if(student==null || !StringUtils.equals(student.getPassword(), password)) {
				return R.error("账号或密码不正确");
			}
			resultDTO.setRole("student");
			resultDTO.setId(student.getId());
			String token = tokenService.generateToken(student.getId(), username, "users", "3");
			resultDTO.setToken(token);
		} else {
			UserInfo userInfo = userService.getUserByName(username);
			if(userInfo==null || !userInfo.getPassword().equals(password)) {
				return R.error("账号或密码不正确");
			}
			resultDTO.setRole(userInfo.getIdentity().equals("1") ? "admin" : "teacher");
			String token = tokenService.generateToken(userInfo.getId(), username, "users", userInfo.getIdentity());
			resultDTO.setToken(token);
			String result = null;
			List<String> clazzCodes = clazzService.getTeacherClazzCodes(userInfo.getId());
			if (resultDTO.getRole().equals("teacher") && !CollectionUtils.isEmpty(clazzCodes)) {
				result = clazzCodes.stream().collect(Collectors.joining(","));
			}
			resultDTO.setId(userInfo.getId());
			resultDTO.setClazzCode(result);
		}
		return R.ok().put("token", resultDTO);
	}


	/**
	 * 后端列表
	 */
	@RequestMapping("/page")
	public R page(String name, Integer pageIndex, Integer pageSize){
		String search = null;
		if (StringUtils.isNotEmpty(name)) {
			search = "%" + name + "%";
		}
		Integer totalCount = userService.findCount(search);
		List<UserInfo> list = userService.findUsers(search, pageIndex, pageSize);
		Pager<UserInfo> pager = new Pager<>(totalCount, list);
		return R.ok().put("data", pager);
	}

	/**
	 * 后端保存
	 */
	@RequestMapping("/saveUser")
	public R saveUser(Long id, String name, String password, String identity, String sex){
		UserInfo userInfo = new UserInfo();
		userInfo.setId(id);
		userInfo.setName(name);
		userInfo.setPassword(password);
		userInfo.setIdentity(identity);
		userInfo.setSex(sex);
		if (userInfo.getId() != null) {
			userService.updateUser(userInfo);
		} else {
			userService.saveUser(userInfo);
		}

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delUser")
	public R delUser(String ids){
		String[] strArr = ids.split(",");
		List<Long> idList = new ArrayList<>();
		for (String str : strArr) {
			idList.add(Long.valueOf(str));
		}
		userService.delUser(idList);
		return R.ok();
	}


	@RequestMapping("/getAllTeacher")
	public R getAllTeacher() {
		List<UserInfo> userInfos = userService.getAllTeacher();
		return R.ok().put("data", userInfos);
	}

	
	/**
	 * 注册
	 */
	@IgnoreAuth
	@PostMapping(value = "/register")
	public R register(@RequestBody UserEntity user){
//    	ValidatorUtils.validateEntity(user);
    	if(userService.selectOne(new EntityWrapper<UserEntity>().eq("username", user.getUsername())) !=null) {
    		return R.error("用户已存在");
    	}
        userService.insert(user);
        return R.ok();
    }

	/**
	 * 退出
	 */
	@GetMapping(value = "logout")
	public R logout(HttpServletRequest request) {
		request.getSession().invalidate();
		return R.ok("退出成功");
	}
	
	/**
     * 密码重置
     */
    @IgnoreAuth
	@RequestMapping(value = "/resetPass")
    public R resetPass(String username, HttpServletRequest request){
    	UserEntity user = userService.selectOne(new EntityWrapper<UserEntity>().eq("username", username));
    	if(user==null) {
    		return R.error("账号不存在");
    	}
    	user.setPassword("123456");
        userService.update(user,null);
        return R.ok("密码已重置为：123456");
    }



	/**
     * 列表
     */
    @RequestMapping("/list")
    public R list( UserEntity user){
       	EntityWrapper<UserEntity> ew = new EntityWrapper<UserEntity>();
      	ew.allEq(MPUtil.allEQMapPre( user, "user")); 
        return R.ok().put("data", userService.selectListView(ew));
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		UserInfo user = userService.getUserById(id);
        return R.ok().put("data", user);
    }
    
    /**
     * 获取用户的session用户信息
     */
    @RequestMapping("/session")
    public R getCurrUser(HttpServletRequest request){
    	Long id = (Long)request.getSession().getAttribute("userId");
        UserInfo user = userService.getUserById(id);
        return R.ok().put("data", user);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody UserEntity user){
//    	ValidatorUtils.validateEntity(user);
    	if(userService.selectOne(new EntityWrapper<UserEntity>().eq("username", user.getUsername())) !=null) {
    		return R.error("用户已存在");
    	}
        userService.insert(user);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
//        ValidatorUtils.validateEntity(user);
    	UserEntity u = userService.selectOne(new EntityWrapper<UserEntity>().eq("username", user.getUsername()));
    	if(u!=null && u.getId()!=user.getId() && u.getUsername().equals(user.getUsername())) {
    		return R.error("用户名已存在。");
    	}
        userService.updateById(user);//全部更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        userService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }
}
